package repository

import (
	"github.com/jinzhu/gorm"
	"golang.org/x/crypto/bcrypt"
	"mall-go/common"
	"mall-go/dto"
	"mall-go/model"
)

type ManagerUserRepo struct {
	DB *gorm.DB
}

func (receiver ManagerUserRepo) Login(adminLoginParam dto.LoginParam) (string, string) {
	//根据用户名查询用户信息
	var adminUser model.NewBeeAdminUser
	receiver.DB.Where("login_user_name = ? and locked = 0", adminLoginParam.UserName).First(&adminUser)
	if adminUser.AdminUserId != 0 {
		//校验密码
		if err := bcrypt.CompareHashAndPassword([]byte(adminUser.LoginPassword), []byte(adminLoginParam.Password)); err != nil {
			return "Fail", "密码错误"
		}
		//生成token
		token, err := common.ReleaseAdminToken(adminUser)
		if err != nil {
			return "Fail", "token发放失败"
		}
		return "Success", token
	}

	return "Fail", "找不到用户"
}

func (receiver ManagerUserRepo) UpdatePassword(adminUserId uint, originalPassword string, newPassword string) bool {
	var adminUser model.NewBeeAdminUser
	receiver.DB.First(&adminUser, adminUserId)
	if adminUser.AdminUserId != 0 {
		//比较密码是否正确
		if err := bcrypt.CompareHashAndPassword([]byte(adminUser.LoginPassword), []byte(originalPassword)); err != nil {
			panic("密码错误")
		}
		password, err := bcrypt.GenerateFromPassword([]byte(newPassword), bcrypt.DefaultCost)
		if err != nil {
			panic("加密失败")
		}
		adminUser.LoginPassword = string(password)
		//修改数据库
		if err := receiver.DB.Model(&adminUser).Update(adminUser).Error; err != nil {
			panic("修改失败")
		}
		return true
	}
	return false
}

func (receiver ManagerUserRepo) UpdateName(adminUserId uint, loginUserName string, nickName string) bool {
	var adminUser model.NewBeeAdminUser
	receiver.DB.First(&adminUser, adminUserId)
	if adminUser.AdminUserId != 0 {
		//设置新名称并修改
		adminUser.LoginUserName = loginUserName
		adminUser.NickName = nickName
		if err := receiver.DB.Model(&adminUser).Update(adminUser).Error; err != nil {
			panic("修改失败")
		}
		return true
	}
	return false
}

func (receiver ManagerUserRepo) Logout() {
	//删除token，我没有token名单就写个空实现
}

func NewManagerUserRepo() ManagerUserRepo {
	db := common.GetDB()
	return ManagerUserRepo{DB: db}
}
